from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from ..database import get_db
from ..models.prompt import Prompt
from ..auth.jwt_handler import get_current_user
from ..models.user import User
from pydantic import BaseModel
from typing import Optional, List
import uuid
import datetime
from datetime import timezone  # 导入timezone以便处理时区信息

router = APIRouter(
    prefix='/prompts',  # 移除/api
    tags=['prompts'],
)

# 定义请求模型
class PromptCreate(BaseModel):
    title: str
    content: str
    description: Optional[str] = None
    version: str  # 修改为str类型，支持语义化版本号
    tags: Optional[str] = None
    model_id: Optional[str] = None
    cover_img: Optional[str] = None

# 定义响应模型
class PromptResponse(BaseModel):
    id: str
    title: str
    content: str
    description: Optional[str] = None
    user_id: str
    is_public: bool
    version: str  # 修改为字符串类型，因为数据库中存储的是'1.0.1'这样的版本号
    tags: Optional[str] = None
    model_id: Optional[str] = None
    cover_img: Optional[str] = None
    created_at: str
    updated_at: str

    # 配置Pydantic模型从SQLAlchemy模型实例创建
    class Config:
        orm_mode = True
        # 自定义JSON编码器以处理UUID和datetime对象
        json_encoders = {
            uuid.UUID: lambda v: str(v),
            datetime.datetime: lambda v: v.isoformat()
        }

# 获取所有提示
@router.get('/', response_model=List[PromptResponse])
def get_prompts(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tag: Optional[str] = Query(None),
    title: Optional[str] = Query(None)
):
    query = db.query(Prompt).filter(Prompt.user_id == current_user.id)

    if tag:
        query = query.filter(Prompt.tags.like(f'%{tag}%'))

    if title:
        query = query.filter(Prompt.title == title)

    prompts = query.order_by(Prompt.created_at.desc()).all()
    
    # 手动转换每个提示对象
    result = []
    for prompt in prompts:
        prompt_dict = {
            "id": str(prompt.id),
            "title": prompt.title,
            "content": prompt.content,
            "description": prompt.description,
            "user_id": str(prompt.user_id),
            "is_public": prompt.is_public,
            "version": str(prompt.version),  # 确保是字符串
            "tags": prompt.tags,
            "model_id": prompt.model_id,
            "cover_img": prompt.cover_img,
            "created_at": prompt.created_at.isoformat() if prompt.created_at else None,
            "updated_at": prompt.updated_at.isoformat() if prompt.updated_at else None
        }
        result.append(prompt_dict)
    
    return result

# 获取单个提示
@router.get('/{prompt_id}', response_model=PromptResponse)
def get_prompt(
    prompt_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    prompt = db.query(Prompt).filter(
        Prompt.id == prompt_id,
        Prompt.user_id == current_user.id
    ).first()
    
    if not prompt:
        raise HTTPException(status_code=404, detail="提示词不存在或无权访问")
    
    # 手动转换提示对象
    return {
        "id": str(prompt.id),
        "title": prompt.title,
        "content": prompt.content,
        "description": prompt.description,
        "user_id": str(prompt.user_id),
        "is_public": prompt.is_public,
        "version": str(prompt.version),
        "tags": prompt.tags,
        "model_id": prompt.model_id,
        "cover_img": prompt.cover_img,
        "created_at": prompt.created_at.isoformat() if prompt.created_at else None,
        "updated_at": prompt.updated_at.isoformat() if prompt.updated_at else None
    }

# 创建新提示
@router.post('/', response_model=PromptResponse)
def create_prompt(
    prompt_data: PromptCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    prompt_id = str(uuid.uuid4())
    new_prompt = Prompt(
        id=prompt_id,
        title=prompt_data.title,
        content=prompt_data.content,
        description=prompt_data.description,
        user_id=current_user.id,
        is_public=True,
        version=prompt_data.version,
        tags=prompt_data.tags,
        model_id=prompt_data.model_id,
        cover_img=prompt_data.cover_img
    )
    db.add(new_prompt)
    db.commit()
    db.refresh(new_prompt)
    
    # 手动转换新创建的提示对象
    return {
        "id": str(new_prompt.id),
        "title": new_prompt.title,
        "content": new_prompt.content,
        "description": new_prompt.description,
        "user_id": str(new_prompt.user_id),
        "is_public": new_prompt.is_public,
        "version": str(new_prompt.version),
        "tags": new_prompt.tags,
        "model_id": new_prompt.model_id,
        "cover_img": new_prompt.cover_img,
        "created_at": new_prompt.created_at.isoformat() if new_prompt.created_at else None,
        "updated_at": new_prompt.updated_at.isoformat() if new_prompt.updated_at else None
    }

# 更新提示
@router.put('/{prompt_id}', response_model=PromptResponse)
def update_prompt(
    prompt_id: str,
    prompt_data: PromptCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    prompt = db.query(Prompt).filter(
        Prompt.id == prompt_id,
        Prompt.user_id == current_user.id
    ).first()
    
    if not prompt:
        raise HTTPException(status_code=404, detail="提示词不存在或无权访问")
    
    # 更新提示信息
    prompt.title = prompt_data.title
    prompt.content = prompt_data.content
    prompt.description = prompt_data.description
    prompt.version = prompt_data.version
    prompt.tags = prompt_data.tags
    prompt.model_id = prompt_data.model_id
    prompt.cover_img = prompt_data.cover_img
    prompt.updated_at = datetime.datetime.now(timezone.utc)
    
    db.commit()
    db.refresh(prompt)
    
    # 手动转换提示对象
    return {
        "id": str(prompt.id),
        "title": prompt.title,
        "content": prompt.content,
        "description": prompt.description,
        "user_id": str(prompt.user_id),
        "is_public": prompt.is_public,
        "version": str(prompt.version),
        "tags": prompt.tags,
        "model_id": prompt.model_id,
        "cover_img": prompt.cover_img,
        "created_at": prompt.created_at.isoformat() if prompt.created_at else None,
        "updated_at": prompt.updated_at.isoformat() if prompt.updated_at else None
    }

# 删除提示
@router.delete('/{prompt_id}')
def delete_prompt(
    prompt_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    prompt = db.query(Prompt).filter(
        Prompt.id == prompt_id,
        Prompt.user_id == current_user.id
    ).first()
    
    if not prompt:
        raise HTTPException(status_code=404, detail="提示词不存在或无权访问")
    
    db.delete(prompt)
    db.commit()
    
    return {"message": "删除成功"}